<!--
 * @Author: your name
 * @Date: 2021-04-05 18:48:21
 * @LastEditTime: 2021-06-01 19:44:09
 * @LastEditors: Please set LastEditors
 * @Description: Q&A 列表
 * @FilePath: /medicine-web/src/views/qanda/index.vue
-->
<template>
  <div class="ques-ans-container">
    <div class="document-container__result">
      <!-- <a-menu v-model="currentTab" mode="horizontal" class="tab-result__outter" v-if="is_menus">
        <a-menu-item v-for="item in tabList" :key="item.label">{{item.label}}</a-menu-item>
      </a-menu> -->
      <tabResultList :sortTabList="['时间']" @downloadAll="downloadAll" @checkAll="checkAll" @collectionAll="collectionAll" @sortStatus="sortStatus" :resultCount="total">
        <div slot="resultList" class="main-search__result-container">
          <div v-if="resultList && resultList.length > 0">
            <div class="main-search__result-item" v-for="item in resultList" :key="item.id">
              <a-checkbox v-model="item.isCheck" @change="onChange(item)"></a-checkbox>
              <ul class="main-search__result-content">
                <li @click.stop="navToDetail(item.id)">
                  <p class="content-regex rich-text" v-html="item.question"></p>
                </li>
                <li>
                  <span class="content-time">时间：<span class="content-regex">{{item.create_time}}</span></span>
                  <span>
                    <userOptions :item="item" @handleClick="userClick"></userOptions>
                  </span>
                </li>
              </ul>
            </div>
          </div>
          <div v-else>
            <emptyData></emptyData>
          </div>
        </div>
      </tabResultList>
      <Pagation v-if="resultList && resultList.length > 0" v-model="pageNum" :total="total"  @handlePage="handlePage" style="margin-top: 48px"></Pagation>
    </div>
  </div>
</template>
<script>
import tabResultList from '@/components/TabResultList/index'
import customBtn from '@/components/CustomBtn/index'
import Pagation from '@/components/Pagation/index'
import userOptions from '@/components/UserOptions/index'
import { mapGetters } from 'vuex'
import emptyData from '@/components/EmptyData/index'
import { arrayToSplitStr1 } from '@/utils/index' 
import { saveAs } from 'file-saver'
import share from '@/utils/share'
export default {
  name: 'questAndAnswer',
  components: { tabResultList, customBtn, Pagation, userOptions, emptyData },
  data () {
    return {
      // currentTab: ['Q&A'],
      // tabList: [
      //   { label: 'Q&A', value: 1 },
      //   { label: '不良反应', value: 2 },
      // ],
      pageNum: 1,
      total: 0,
      resultList: [],
      checkList: [],
      isInit: false, // 是否初始化
    }
  },
  methods: {
    async downloadAll () {
      if (!this.getCookie('uid')) {
        this.msgInfo('您还没有登录，正在跳转至登录界面...')
        setTimeout(() => {
          this.$router.push('/login')
        }, 1500)
        return
      }
      if (!this.checkList || this.checkList.length === 0) {
        this.msgInfo('请选择您要下载的数据')
        return
      }
      const download = await this.$action('doDownload', { user_id: this.getCookie('uid'), ids: arrayToSplitStr1(this.checkList, 'id'), module: 5 })
      if (download) {
        let ids = arrayToSplitStr1(this.checkList, 'id')
        // this.msgSuccess('批量下载成功')
        // for (const item of this.checkList) {
        //   if (item && item.annex && item.annex.length > 0) {
        //     saveAs(this.$uploadUrl + item.annex[0], item.annex[0].split('/')[item.annex[0].split('/').length - 1])
        //   }
        // }
        this.$action('getFileBlocBatch', { ids: ids, user_id: this.getCookie('uid'), module: 5 })
      } else {
        this.msgSuccess('批量下载失败, 请稍后重试.')
      }
    },
    checkAll (isCheck) {
      this.resultList.map(item => {
        item.isCheck = isCheck
      })
      if (isCheck) {
        this.checkList = this.resultList
      } else {
        this.checkList = []
      }
    },
    sortStatus (sort) {
      if (sort.tab === '时间' && sort.active === false) {
        this.filterMap.order = 'create_time'
        this.filterMap.order_by = 'asc'
      } else if (sort.tab === '时间' && sort.active === true) {
        this.filterMap.order = 'create_time'
        this.filterMap.order_by = 'desc'
      }
      this.fetchData()
    },
    async collectionAll () {
      if (!this.getCookie('uid')) {
        this.msgInfo('您还没有登录，正在跳转至登录界面...')
        setTimeout(() => {
          this.$router.push('/login')
        }, 1500)
        return
      }
      if (!this.checkList || this.checkList.length === 0) {
        this.msgInfo('请选择您要收藏的数据')
        return
      }
      const res = await this.$action('doCollection', { user_id: this.getCookie('uid'), ids: arrayToSplitStr1(this.checkList, 'id'), module: 5 })
      if (res) {
        this.msgSuccess('批量收藏成功')
        for (let item of this.resultList.filter(item => item.isCheck == true)) {
          item.isCollect = true
        }
      } else {
        this.msgError('批量收藏失败')
      }
    },
    onChange (rawData) {
      console.log('onChange===========', rawData)
      if (rawData.isCheck) {
        this.checkList.push(rawData)
      } else {
        this.checkList = this.checkList.filter(item => item.id != rawData.id)
      }
    },
    handleStatistics () {

    },
    handlePage (count) {
      console.log('handlePage=============', count)
      this.pageNum = count
      this.fetchData()
    },
    async userClick (rawData) {
      if (!this.getCookie('uid')) {
        this.msgInfo('您还没有登录，正在跳转至登录界面...')
        setTimeout(() => {
          this.$router.push('/login')
        }, 1500)
        return
      }
      console.log('userClick=============', rawData)
      if (rawData.type === 'download') {
        if (rawData && rawData.data && rawData.data.annex && rawData.data.annex.length > 0) {
          const download = await this.$action('doDownload', { user_id: this.getCookie('uid'), ids: rawData.data.id, module: 5 })
          if (download) {
            // this.msgSuccess('下载成功')
            // saveAs(this.$uploadUrl + rawData.data.annex[0], rawData.data.annex[0].split('/')[rawData.data.annex[0].split('/').length - 1])
            await this.$action('getFileBloc', { id: rawData.data.id, user_id: this.getCookie('uid'), module: 5 })
          } else {
            this.msgSuccess('下载失败, 请稍后重试.')
          }
        } else {
          this.$message.info('暂无文件附件，无法下载。')
        }
      } else if (rawData.type === 'collection') { // 收藏
        let res
        if (rawData.active) {
          res = await this.$action('doCollection', { user_id: this.getCookie('uid'), ids: rawData.data.id, module: 5 })
          if (res) {
            this.msgSuccess('收藏成功')
          } else {
            this.msgError('收藏失败')
          }
        } else {
          res = await this.$action('cancelCollection', { user_id: this.getCookie('uid'), id: rawData.data.id })
          if (res) {
            this.msgSuccess('取消收藏成功')
          } else {
            this.msgError('取消收藏失败')
          }
        }
      } else if (rawData.type === 'xinlang') { // 分享新浪
        share.toShareXinLang(document.location.protocol + '//' + window.location.host + `/qanda/index?id=${rawData.data.id}`, rawData.data.question ? rawData.data.question.replace(/<[^>]+>|&[^>]+;/g, '') : '')
      } else if (rawData.type === 'qq') { // 分享QQ
        share.toShareQQZone(document.location.protocol + '//' + window.location.host + `/qanda/index?id=${rawData.data.id}`, rawData.data.question ? rawData.data.question.replace(/<[^>]+>|&[^>]+;/g, '') : '', rawData.data.answer ? rawData.data.answer.replace(/<[^>]+>|&[^>]+;/g, '') : '', '')
      } else if (rawData.type === 'wechat') { // 分享微信
        share.toShareWeChat(document.location.protocol + '//' + window.location.host + `/qanda/index?id=${rawData.data.id}`)
      }
    },
    navToDetail (id) {
      this.$router.push({ path: '/qanda/detail', query: { id } })
    },
    async fetchData () {
      let info = {
        limit: 10,
        page: this.pageNum
      }
      if (this.filterMap && Object.keys(this.filterMap).length > 0) {
        info = Object.assign(info, this.filterMap)
      }
      console.log('getQAList filter', info)
      const res = await this.$action('getQAList', info)
      console.log('getQAList', res)
      this.total = res.total_number || 0
      this.$action('setTotalNum', this.total)
      let dataList = res.data_list
      // this.$action('resetSort', true)
      if (!dataList || dataList.length === 0) {
        this.resultList = []
        return
      }
      dataList.map(item => {
        item.isShare = false
        item.isCollect = false
        item.isDownload = false
        item.isCheck = false
      })
      this.resultList = dataList
      console.log('getQAList map', this.resultList)
      if (this.searchValue) {
        this.$nextTick(() => {
          const contentEle = document.getElementsByClassName('content-regex')
          for (let item of contentEle) {
            const regex = new RegExp(this.searchValue, 'g')
            item.innerHTML = item.innerText
            item.innerHTML = item.innerHTML.replace(regex, '<b class="high-light" style="color: #FFBA00">' + this.searchValue + '</b>')
          }
          this.$forceUpdate()
        })
      }
    }
  },
  mounted () {
    this.isInit = true
    this.fetchData()
  },
  // beforeDestroy () {
  //   if (this.$route.path.indexOf('/simple/search') != -1) {
  //     return
  //   }
  //   this.$action('setFilter', {})
  // },
  computed: {
    ...mapGetters({
      filterMap: 'filterMap',
      searchValue: 'searchValue'
    })
  },
  watch: {
    filterMap: {
      handler (val, old) {
        if (val && val.keywords) {
          this.$nextTick(() => {
            const contentEle = document.getElementsByClassName('content-regex')
              for (let item of contentEle) {
              const regex = new RegExp(this.searchValue, 'g')
              item.innerHTML = item.innerText
              item.innerHTML = item.innerHTML.replace(regex, '<b class="high-light" style="color: #FFBA00">' + val.keywords + '</b>')
            }
            this.$forceUpdate()
          })
        }
        if (val.isInit == false) { // 搜索点击按钮
          this.isInit = val.isInit
        }
        if (this.isInit) {
          this.isInit = false
          return
        }
        this.pageNum = 1
        this.fetchData()
      },
      deep: true
    },
    searchValue: function (val, oldVal) {
      const contentEle = document.getElementsByClassName('content-regex')
      for (let item of contentEle) {
        const regex = new RegExp(val, 'g')
        item.innerHTML = item.innerText
        item.innerHTML = item.innerHTML.replace(regex, '<b class="high-light" style="color: #FFBA00">' + val + '</b>')
      }
    },
  }
}
</script>
<style lang="scss" scoped>
@import '~@/assets/styles/flex.scss';
@import '~@/assets/styles/common.scss';
.ques-ans-container {
  width: 1200px;
  margin: 0 auto;
  padding: 32px 0px 88px 0px;
  /deep/ .a-btn-container .btn-pattern {
    width: 132px;
    height: 37px;
    font-size: 14px;
    color: #555;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.21);
  }
  .document-container__result {
    // margin-top: 28px;
    .main-search__result-container {
      .main-search__result-item {
        @include flex-def;
        .main-search__result-content {
          width: 100%;
          margin-left: 8px;
          li {
            font-size: 14px;
            color: #555;
            cursor: pointer;
          }
          li:nth-child(2) {
            @include flex-def;
            @include flex-zBetween;
            @include flex-cCenter;
          }
        }
      }
    }
  }
}
</style>
